import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useProjectStore = defineStore('project', () => {
  // 状态
  const inTalkProjects = ref([])
  const constructionProjects = ref([])  // 建设中项目
  const landApprovalProjects = ref([])  // 征地报批项目
  const completionProjects = ref([])    // 竣工验收项目
  // 在状态定义部分添加
const followUpHistory = ref({}) // 结构: { [projectId]: [跟进记录数组] }
  
  // 新增状态
const contracts = ref({}) // 结构: { [projectId]: 合同对象 }

const auditRecords = ref({
     3: [
      {
        id: 1003,
        time: "2023-07-20 09:00:00",
        status: "已通过",
        auditor: "王先生",
        department: "建设单位",
        comment: "施工图设计符合规范",
        step:1
      },
      {
        id: 1004,
        time: "2023-07-21 09:00:00",
        status: "已通过",
        auditor: "李先生",
        department: "建设发展局",
        comment: "施工图设计符合规范",
        step:2
      }
    ],
    6:[
      {
             
        id: 1006,
        time: "2023-07-21 09:00:00",
        status: "已通过",
        auditor: "李先生",
        department: "建设发展局",
        comment: "施工图设计符合规范",
        step:1
      
      }
    ]
  }) // 审核记录存储，使用对象存储，key为projectId
  const files = ref({
  3: [
    {
      id: 3001,
      name: '新能源项目合同.pdf',
      size: 5242880, // 5MB
      type: 'pdf',
      uploadTime: '2023-06-15 11:20:00',
      uploader: '张经理'
    },
    {
      id: 3002,
      name: '施工图纸.zip',
      size: 10485760, // 10MB
      type: 'zip',
      uploadTime: '2023-06-20 16:45:00',
      uploader: '李工'
    }
  ],
  6: [
    {
      id: 6001,
      name: '物流园规划图.pdf',
      size: 3145728, // 3MB
      type: 'pdf',
      uploadTime: '2023-07-12 14:00:00',
      uploader: '王设计师'
    }
  ]
})
  // 初始化数据
  const initData = () => {
    inTalkProjects.value = [
      {
        id: 1,
        projectName: '智能制造产业园一期',
        projectCode: 'XM20230001',
        investor: 'ABC投资集团',
        contactPerson: '张经理',
        industryCategory: '智能制造',
        parkName: '高新科技园区',
        status: '进行中'
      },
      {
        id: 2,
        projectName: '生物医药研发中心',
        projectCode: 'XM20230002',
        investor: 'XYZ医药公司',
        contactPerson: '李总监',
        industryCategory: '生物医药',
        parkName: '生命科学园区',
        status: '筹备中'
      }
    ]
    
  constructionProjects.value = [
      {
        id: 3,
        type: 'independent',
        projectName: '新能源研发中心',
        projectCode: 'XM20230003',
        investor: '新能源科技',
        address:'中关村一街',
        contactPerson: '王总监',
        contactPhone:'1278593266',
        industryCategory: '新能源',
        parkName: '绿色科技园区',
        status: '审核中',
        signDate: '2023-06-15',
        state:'construction',
        projectDuration: 24, // 默认12个月
        constructionStartDate: '2024-03-23', // 新增开始施工日期
        totalInvestment: 1,          // 计划总投资(万元)
        fixedAssetInvestment:1,     // 固定资产总投资(万元)
        landArea: 1,                 // 用地面积(亩)
        annualOutputValue: 1,        // 产值(万元/年)
        annualTaxRevenue: 1         // 纳税额(万元/年)
      },
      {
  id: 4,
  type: 'independent',
  projectName: '人工智能创新中心',
  projectCode: 'XM20230004',
  investor: '深蓝科技',
  address: '中关村三街',
  contactPerson: '陈技术总监',
  contactPhone: '13812345678',
  industryCategory: '人工智能',
  parkName: '数字科技园区',
  status: '施工中',
  signDate: '2023-09-10',
  state: 'construction',
  projectDuration: 18,
  constructionStartDate: '2024-01-15',
  totalInvestment: 1,          // 计划总投资(万元)
  fixedAssetInvestment: 1,     // 固定资产总投资(万元)
  landArea: 1,                 // 用地面积(亩)
  annualOutputValue: 1,        // 产值(万元/年)
  annualTaxRevenue: 1         // 纳税额(万元/年)
},
{
  id: 6,
  type: 'rental',
  projectName: '智慧物流产业园',
  projectCode: 'XM20230006',
  investor: '顺丰速运有限公司',
  address: '临港物流园区18号',
  contactPerson: '赵运营总监',
  contactPhone: '18812345678',
  industryCategory: '现代物流',
  parkName: '国际物流枢纽园区',
  status: '已完成',
  signDate: '2023-07-12',
  state: 'construction',
  projectDuration: 18,
  constructionStartDate: '2023-10-01',
  totalInvestment:1,          // 计划总投资(万元)
  fixedAssetInvestment: 1,     // 固定资产总投资(万元)
  landArea:1,                 // 用地面积(亩)
  annualOutputValue: 1,        // 产值(万元/年)
  annualTaxRevenue: 1         // 纳税额(万元/年)
  }
    ]

    // 征地报批项目数据
    landApprovalProjects.value = [
      {
        id: 5,
        type: 'rental',
        projectName: '智慧物流产业园',
        projectCode: 'XM20230005',
        investor: '顺丰速运有限公司',
        address: '临港物流园区18号',
        contactPerson: '赵运营总监',
        contactPhone: '18812345678',
        industryCategory: '现代物流',
        parkName: '国际物流枢纽园区',
        status: '征地报批中',
        signDate: '2023-07-12',
        state: 'landApproval',
        projectDuration: 18,
        constructionStartDate: '2023-10-01',
        totalInvestment: 1,          // 计划总投资(万元)
        fixedAssetInvestment:1,     // 固定资产总投资(万元)
        landArea:1,                 // 用地面积(亩)
        annualOutputValue: 1,        // 产值(万元/年)
        annualTaxRevenue: 1         // 纳税额(万元/年)
      }
    ]

    // 竣工验收项目数据
    completionProjects.value = [
      {
        id: 6,
        type: 'independent',
        projectName: '高端装备制造基地',
        projectCode: 'XM20230006',
        investor: '重工集团',
        address: '装备制造园区1号',
        contactPerson: '刘总工程师',
        contactPhone: '13987654321',
        industryCategory: '装备制造',
        parkName: '高端装备园区',
        status: '竣工验收',
        signDate: '2022-11-05',
        state: 'completion',
        projectDuration: 24,
        constructionStartDate: '2023-02-15',
        totalInvestment: 1,          // 计划总投资(万元)
        fixedAssetInvestment: 1,     // 固定资产总投资(万元)
        landArea:1,                 // 用地面积(亩)
        annualOutputValue: 1,        // 产值(万元/年)
        annualTaxRevenue: 1         // 纳税额(万元/年)
        
      }
    ]
  

      // 初始化跟进记录
    followUpHistory.value = {
      1: [ // 项目ID为1的测试数据
        {
          id: 1,
          content: '初始跟进测试',
          createdAt: new Date().toISOString(),
          creator: '系统'
        }
      ]
    }
  }

  // 新增状态：跟进人列表
const followers = ref([
  { id: 1, name: '张三'},
  { id: 2, name: '李四'},
  { id: 3, name: '王五'}
])



  // 新增方法：更新项目
  const updateProject = async (id, newData) => {
    let index = inTalkProjects.value.findIndex(p => p.id == id)
    let isInTalk = true
    
    if (index === -1) {
      index = signedProjects.value.findIndex(p => p.id == id)
      isInTalk = false
    }
    
    if (index !== -1) {
      const updatedProject = { 
        ...(isInTalk ? inTalkProjects.value[index] : signedProjects.value[index]),
        ...newData
      }
      
      if (isInTalk) {
        inTalkProjects.value.splice(index, 1, updatedProject)
      } else {
        signedProjects.value.splice(index, 1, updatedProject)
      }
      return true
    }
    return false
  }

   // 更新项目信息
  const updateProject1 = (updatedProject) => {
    let targetList
    switch(updatedProject.state) {
      case 'construction':
        targetList = constructionProjects.value
        break
      case 'landApproval':
        targetList = landApprovalProjects.value
        break
      case 'completion':
        targetList = completionProjects.value
        break
      default:
        targetList = inTalkProjects.value
    }
    
    const index = targetList.findIndex(p => p.id === updatedProject.id)
    if (index !== -1) {
      targetList[index] = {
        ...updatedProject,
        type: updatedProject.type,
        signDate: updatedProject.signDate || targetList[index].signDate
      }
      return true
    }
    return false
  }

  // 新增方法：创建项目
  const createProject = async (projectData) => {
    const newProject = {
      ...projectData,
      id: Date.now(), // 生成唯一ID
      status: projectData.status || '进行中'
    }
    
    if (newProject.status === '已签约') {
      newProject.signDate = new Date().toISOString().split('T')[0]
      signedProjects.value.unshift(newProject)
    } else {
      inTalkProjects.value.unshift(newProject)
    }
    return newProject.id // 返回新项目ID
  }

  // 确保有以下方法
const assignFollower = (projectId, followerId) => {
  const allProjects = [...inTalkProjects.value, ...signedProjects.value]
  const project = allProjects.find(p => p.id === projectId)
  
  if (project) {
    const follower = followers.value.find(f => f.id === followerId)
    if (follower) {
      project.follower = follower.name
      project.followerId = follower.id
      
      return true
    }
  }
  return false
}


  // 转移项目到签约列表
  const moveToSigned = (projectId) => {
    const index = inTalkProjects.value.findIndex(p => p.id === projectId)
    if (index !== -1) {
      const project = { 
        ...inTalkProjects.value[index],
        status: '已签约',
        signDate: new Date().toISOString().split('T')[0] // 添加签约日期
      }
      inTalkProjects.value.splice(index, 1)
      signedProjects.value.unshift(project) // 添加到签约列表开头
      return true
    }
    return false
  }
  

 // 转移项目到建设中列表
  const moveToConstruction = (projectId) => {
    const index = inTalkProjects.value.findIndex(p => p.id === projectId)
    if (index !== -1) {
      const project = { 
        ...inTalkProjects.value[index],
        status: '建设中',
        state: 'construction',
        signDate: new Date().toISOString().split('T')[0]
      }
      inTalkProjects.value.splice(index, 1)
      constructionProjects.value.unshift(project)
      return true
    }
    return false
  }

  // 转移项目到征地报批列表
  const moveToLandApproval = (projectId) => {
    const index = constructionProjects.value.findIndex(p => p.id === projectId)
    if (index !== -1) {
      const project = { 
        ...constructionProjects.value[index],
        status: '征地报批中',
        state: 'landApproval',
        approvalDate: new Date().toISOString().split('T')[0]
      }
      constructionProjects.value.splice(index, 1)
      landApprovalProjects.value.unshift(project)
      return true
    }
    return false
  }

  // 转移项目到竣工验收列表
  const moveToCompletion = (projectId) => {
    const index = landApprovalProjects.value.findIndex(p => p.id === projectId)
    if (index !== -1) {
      const project = { 
        ...landApprovalProjects.value[index],
        status: '竣工验收',
        state: 'completion',
        completionDate: new Date().toISOString().split('T')[0]
      }
      landApprovalProjects.value.splice(index, 1)
      completionProjects.value.unshift(project)
      return true
    }
    return false
  }

   // 添加新项目
  const addProject = (project) => {
    const newProject = {
      ...project,
      id: project.id || Date.now(),
      status: project.status || '审核中',
      state: project.state || 'inTalk',
      type: project.type,
      signDate: project.signDate || new Date().toISOString().split('T')[0]
    }
    
    // 根据状态决定添加到哪个列表
    switch(newProject.state) {
      case 'construction':
        constructionProjects.value.unshift(newProject)
        break
      case 'landApproval':
        landApprovalProjects.value.unshift(newProject)
        break
      case 'completion':
        completionProjects.value.unshift(newProject)
        break
      default:
        inTalkProjects.value.unshift(newProject)
    }
  }

  // 模拟API获取数据
  const fetchInTalkProjects = async () => {
    // 这里可以是实际的API调用
    // const res = await api.getInTalkProjects()
    // inTalkProjects.value = res.data
  }
  
  const fetchSignedProjects = async () => {
    // 这里可以是实际的API调用
    // const res = await api.getSignedProjects()
    // signedProjects.value = res.data
  }
  // 获取在谈项目详情
const getInTalkProjectById = (id) => {
  return inTalkProjects.value.find(project => project.id == id) || null
}

// 获取签约项目详情
const getSignedProjectById = (id) => {
  return signedProjects.value.find(project => project.id === id) || null
}

// 添加跟进记录
const addFollowUpRecord = (projectId, content) => {
  try {
    if (!followUpHistory.value[projectId]) {
      followUpHistory.value[projectId] = []
    }
    
    const newRecord = {
      id: Date.now(),
      content,
      createdAt: new Date().toISOString(),
      creator: '当前用户' // 实际应从用户系统获取
    }
    
    followUpHistory.value[projectId].unshift(newRecord)
    return newRecord
  } catch (error) {
    console.error('添加跟进记录失败:', error)
    throw error // 重新抛出以便组件捕获
  }
}

// 获取项目跟进记录
const getFollowUpRecords = (projectId) => {
  return followUpHistory.value[projectId] || []
}

// 新增删除方法
const deleteProject = (projectId) => {
  const lists = {
      inTalk: inTalkProjects.value,
      construction: constructionProjects.value,
      landApproval: landApprovalProjects.value,
      completion: completionProjects.value
    }
    
    for (const [type, list] of Object.entries(lists)) {
      const index = list.findIndex(p => p.id == projectId)
      if (index !== -1) {
        list.splice(index, 1)
        return { success: true, type }
      }
    }
    return { success: false }
}

// 新增方法：签订合同
const signContract = (projectId, contractData) => {
  const project = getProjectById(projectId)
  if (!project) return false
  
  // 创建合同记录
  contracts.value[projectId] = {
    ...contractData,
    id: `contract-${Date.now()}`,
    projectId,
    createdAt: new Date().toISOString(),
    status: 'active'
  }

  // 更新项目状态
  project.status = '已签约'
  project.contractId = contracts.value[projectId].id

  return true
}

// 新增方法：获取项目合同
const getProjectContract = (projectId) => {
  return contracts.value[projectId] || null
}


// 获取项目详情
  const getProjectById = (id) => {
    const allProjects = [
      ...inTalkProjects.value,
      ...constructionProjects.value,
      ...landApprovalProjects.value,
      ...completionProjects.value
    ]
    return allProjects.find(project => project.id == id) || null
  }

// 添加审核记录方法
  const addAuditRecord = (projectId, record) => {
    if (!auditRecords.value[projectId]) {
      auditRecords.value[projectId] = []
    }
    auditRecords.value[projectId].unshift({
      ...record,
      id: Date.now(), // 唯一ID
      time: new Date().toISOString() // 自动记录时间
    })
  }
  
  // 获取项目审核记录
  const getProjectAuditRecords = (projectId) => {
    return auditRecords.value[projectId] || []
  }

// 添加项目文件
const addProjectFiles = (projectId, newFiles) => {
  if (!files.value[projectId]) {
    files.value[projectId] = []
  }
  
  // 过滤掉重复文件
  const existingFileNames = files.value[projectId].map(f => f.name)
  const uniqueFiles = newFiles.filter(file => !existingFileNames.includes(file.name))
  
  // 添加新文件
  files.value[projectId].push(...uniqueFiles.map(file => ({
    ...file,
    id: Date.now(), // 生成唯一ID
    uploadTime: new Date().toISOString(),
    uploader: '当前用户' // 实际项目中应从用户信息获取
  })))
  
  return uniqueFiles.length // 返回成功添加的文件数量
}

const getProjectFiles = (projectId) => {
  return files.value[projectId] || []
}

// 删除项目文件
const deleteProjectFile = (projectId, fileId) => {
  if (files.value[projectId]) {
    const initialLength = files.value[projectId].length
    files.value[projectId] = files.value[projectId].filter(file => file.id !== fileId)
    return initialLength !== files.value[projectId].length
  }
  return false
}

  // 初始化数据
  initData()

  return {
    inTalkProjects,
    constructionProjects,
   landApprovalProjects,
   completionProjects,
   auditRecords,
   files,

    // 新增方法
    getProjectById,
    updateProject,
    createProject,
     moveToConstruction,
   moveToLandApproval,
   moveToCompletion,
   updateProject1,
   addAuditRecord,
   getProjectAuditRecords,
   addProjectFiles,
   getProjectFiles,
   deleteProjectFile,
    // 原有方法
    moveToSigned,
    addProject,
    fetchInTalkProjects,
    fetchSignedProjects,
    getInTalkProjectById,
    getSignedProjectById,
 
      // ...其他导出
  assignFollower,
    followers,
    addFollowUpRecord,
    getFollowUpRecords,
    deleteProject,
      signContract,
  getProjectContract,
  contracts,
  followUpHistory
  }
})